<template>
	<gracePage headerBG="#FFFFFF" :headerIndex="9999999" :bounding="false">
		<view slot="gHeader" class="grace-bg-white">
			<view class="grace-header-body grace-relative">
				<text class="grace-header-icons your-icon iconxiangzuo font-size-34" style="" @tap="appFn.navigateBackFn"></text>
				<!-- 中间内容 -->
				<view class="grace-header-content-noflex py-1-5 px-3 text-center"><text class="grace-h4 text-center font-size-36" style="font-size:36rpx;">我的订单</text></view>
				<!-- 消息按钮 -->
				<text class="grace-header-icons my-icons"></text>
			</view>
		</view>
		<view slot="gBody" class="grace-flex-v1" id="gBody">
			<view style="padding:20rpx 25rpx;background: #F5F5F5;" class="z-index-9999999" id="nav">
				<graceNavBar
					:items="tabs"
					:currentIndex="swiperCurrentIndex"
					@change="navChange"
					activeColor="#1CA376"
					textAlign="center"
					activeDirection="center"
					activeLineBg="#1CA376"
				></graceNavBar>
			</view>
			<swiper :style="{ height: mainHeight + 'px' }" :current="swiperCurrentIndex" @change="swiperChange">
				<swiper-item v-for="(item, index) in tabs" :key="index">
					<scroll-view scroll-y :style="{ height: mainHeight + 'px' }" @scrolltolower="scrollend">
						<!-- 空数据 -->
						<view style="margin-top:150rpx;" v-if="orders[index].length === 0 && loadingTypes[index] === 5">
							<graceEmpty>
								<view slot="img" class="empty-view">
									<!-- 请根据您的项目要求制作并更换为空图片 -->
									<image class="empty-img" mode="widthFix" src="/static/images/loding.png"></image>
								</view>
								<text slot="text" class="grace-text-small grace-margin-top grace-gray">暂无订单信息~</text>
							</graceEmpty>
						</view>
						<view
							class="grace-order grace-box-shadow pb-3"
							:class="{ lodingAnimation: orders[index].length != 0 }"
							v-if="orders[index].length != 0"
							v-for="(order, orderIndex) in orders[index]"
							:key="orderIndex"
							@tap="gotoOrderFn(order.order_id, index, order.main_order_id)"
						>
							<view class="grace-space-between grace-flex-center">
								<text class="grace-order-number">订单号 : {{ order.order_sn }}</text>
								<view class="">
									<text class="grace-text grace-red" style="margin-left:10rpx;">{{ order.is_free === '1' ? '0元购订单' : '' }}{{ order.status_text }}</text>
								</view>
							</view>
							<!-- 以商铺为单位进行循环 -->
							<view class="grace-title"><text class="grace-black">臻选优品</text></view>
							<!-- 循环订单商品 -->
							<view class="grace-order-goods" v-for="(goods, indexGoods) in order.list" :key="indexGoods">
								<image :src="goods.goods_img" class="grace-order-goods-img" mode="widthFix"></image>
								<text class="grace-order-goods-name">{{ goods.goods_name }}</text>
								<view class="grace-order-goods-price">
									<text class="grace-red">￥{{ goods.goods_price }}</text>
									<text class="grace-order-goods-num">x {{ goods.goods_number }}</text>
								</view>
							</view>
							<!-- 快递费用 -->
							<view class="grace-space-between grace-flex-center">
								<text class="grace-order-number"></text>
								<view class="">
									邮费
									<text class="grace-text grace-red" style="margin-left:10rpx;">￥{{ order.shipping_fee }}</text>
								</view>
							</view>
							<!-- 总价 -->
							<view class="grace-space-between grace-flex-center">
								<text class="grace-order-number"></text>
								<view class="">
									订单总价
									<text class="grace-text grace-red" style="margin-left:10rpx;">￥{{ order.is_free === '1' ? '0.00' : order.goods_amount }}</text>
								</view>
							</view>
							<!-- 支付价格 -->
							<view class="grace-space-between grace-flex-center">
								<text class="grace-order-number"></text>
								<view class="">
									共{{ order.count }}款商品 订单金额:
									<text class="grace-text grace-red" style="margin-left:10rpx;">￥{{ order.order_amount }}</text>
								</view>
							</view>
							<!-- 订单底部 -->
							<view class="grace-order-footer grace-nowrap">
								<text class="grace-order-number">{{ order.add_time | filterTime }}</text>
								<!-- 订单状态码，1为未付款，2为已付款，3为已发货，4为已收货，5为退货中，6为已取消 main_order_id-->
								<text
									class="grace-order-btn grace-order-btn-red"
									:class="{ 'grace-order-btn-gray': order.main_order_id != '0' }"
									v-if="order.status_code === 1"
									@click.stop="callPayFn(order.order_id, order.main_order_id)"
								>
									付款
								</text>
								<text class="grace-order-btn" v-if="order.status_code === 2">查看订单</text>
								<text class="grace-order-btn" v-if="order.status_code === 3" @click.stop="gotoLogistice(order.order_id)">查看物流</text>
								<text class="grace-order-btn grace-order-btn-blue" v-if="order.status_code === 3" @click.stop="takeOverFn(order.order_id)">确认收货</text>
								<text class="grace-order-btn" v-if="order.status_code === 4">立即评价</text>
								<text class="grace-order-btn" v-if="order.status_code === 5">退货中</text>
							</view>
						</view>
						<view style="height: 60rpx;"></view>
						<!-- 每个选项卡都有一个自己的加载更多  -->
						<graceLoading :loadingType="loadingTypes[index]"></graceLoading>
					</scroll-view>
				</swiper-item>
			</swiper>
			<!-- 全屏 Loading -->
			<graceFullLoading :graceFullLoading="graceFullLoading" logoUrl="/static/images/lodingbg.png"></graceFullLoading>
		</view>
	</gracePage>
</template>
<script>
import gracePage from '@/graceUI/components/gracePage.vue';
import graceEmpty from '@/graceUI/components/graceEmptyNew.vue';
import graceNavBar from '@/graceUI/components/graceNavBar.vue';
import graceLoading from '@/graceUI/components/graceLoading.vue';
import graceFullLoading from '@/graceUI/components/graceFullLoading.vue';
// var request = require('@/graceUI/jsTools/request.js');
var moment = require('@/common/js/moment.js');
import { mapActions } from 'vuex';
export default {
	data() {
		return {
			// 全屏加载
			graceFullLoading: false,
			swiperCurrentIndex: 0,
			tabs: ['全部', '待付款', '待发货', '待收货'],
			tabsCode: ['all', '3', '1', '5'],
			tabsCodeIndex: 0,
			mainHeight: 400,
			// 订单数据  订单数组和订单状态数组元素一致
			orders: [[], [], [], []],
			// 订单页码
			pages: [1, 1, 1, 1],
			// 加载状态
			loadingTypes: [3, 3, 3, 3],
			// 阻止重复提交
			submitPay: true
		};
	},
	onReady: function() {
		setTimeout(() => {
			uni.createSelectorQuery()
				.select('#gBody')
				.fields({ size: true }, res => {
					uni.createSelectorQuery()
						.select('#nav')
						.fields({ size: true }, res2 => {
							this.mainHeight = res.height - res2.height;
						})
						.exec();
				})
				.exec();
		}, 1000);
	},
	onShow() {
		uni.$on('takeOverStatus', () => {
			this.reloadFn();
			// 清除监听
			uni.$off('takeOverStatus');
		});
	},
	onLoad: function(e) {
		if (e.index) {
			this.swiperCurrentIndex = parseInt(e.index);
		}
		this.__init();
	},
	watch: {
		swiperCurrentIndex: function(val) {
			// 如果切换时尚未读取数据则读取
			if (this.orders[this.swiperCurrentIndex].length < 1 && this.loadingTypes[this.swiperCurrentIndex] == 3) {
				this.reloadFn();
			}
		}
	},
	methods: {
		...mapActions(['getUserInfo']),
		async __init() {
			this.getOrders();
		},
		navChange: function(e) {
			this.swiperCurrentIndex = e;
		},
		swiperChange: function(e) {
			var index = e.detail.current;
			this.swiperCurrentIndex = index;
		},
		scrollend: function(e) {
			// 避免重复加载
			if (this.loadingTypes[this.swiperCurrentIndex] != 3) {
				return;
			}
			this.getOrders();
		},
		reloadFn() {
			this.pages = [1, 1, 1, 1];
			this.orders = [[], [], [], []];
			this.loadingTypes = [3, 3, 3, 3];
			this.getOrders('swiperMove');
		},
		async getOrders(text) {
			if (text == 'swiperMove') this.graceFullLoading = true;
			this.loadingTypes.splice(this.swiperCurrentIndex, 1, 1);

			// 订单状态，"all"查全部，未付款3，已付款1，已发货5
			// 接口地址组合
			let options = {
				act: 'get_order',
				status: this.tabsCode[this.swiperCurrentIndex],
				page: this.pages[this.swiperCurrentIndex]
			};

			this.$HTTP.post('/api/api.php', options, { token: true }).then(res => {
				// 返回为空  未找到订单
				if (res.error) {
					this.loadingTypes.splice(this.swiperCurrentIndex, 1, 5);
				} else {
					if (this.pages[this.swiperCurrentIndex] == 1) {
						this.orders.splice(this.swiperCurrentIndex, 1, res.order);
					} else {
						this.orders[this.swiperCurrentIndex] = this.orders[this.swiperCurrentIndex].concat(res.order);
					}
					// 避免数据处乱
					var arr = this.orders;
					for (var i = 0; i < arr.length; i++) {
						if (i === this.swiperCurrentIndex) continue;
						arr[i] = [];
					}
					console.log('arr', arr);
					this.orders = arr;
					this.pages[this.swiperCurrentIndex]++;
					this.loadingTypes.splice(this.swiperCurrentIndex, 1, 3);
				}
				if (text == 'swiperMove') {
					setTimeout(() => {
						this.graceFullLoading = false;
					}, 500);
				}
			});
		},
		gotoOrderFn(orderId, index, mainId) {
			console.log('gotoOrderFn', orderId, index);
			console.log(index == 1, mainId, mainId != '0' && index == 1);
			if (mainId != '0' && index == 1) return;
			console.log('gotoOrderFn', orderId, index);
			switch (index) {
				case 0:
					break;
				case 1:
					this.navigateTo({
						url: '/pages/order/orderContinue/orderContinue?orderId=' + orderId
					});
					break;
				case 2:
					this.navigateTo({
						url: '/pages/order/orderDetails/orderDetails?orderId=' + orderId + '&index=' + this.swiperCurrentIndex
					});
					break;
				case 3:
					this.navigateTo({
						url: '/pages/order/orderDetails/orderDetails?orderId=' + orderId + '&index=' + this.swiperCurrentIndex
					});
					break;
			}
		},
		async callPayFn(orderId, mainId) {
			if (mainId != '0') return;
			if (this.submitPay) {
				this.submitPay = false;
				// 直接付款 吊起微信支付
				// #ifdef MP-WEIXIN || MP-QQ
				let options = {
					act: 'continue_pay',
					order_id: orderId,
					pay_type: 'miniapp'
				};
				// #endif
				// #ifdef APP-PLUS
				let options = {
					act: 'continue_pay',
					order_id: orderId,
					pay_type: 'wechat_app'
				};
				// #endif

				let res = await this.$HTTP.post('/api/api.php', options, { token: true });

				// #ifdef MP-WEIXIN || MP-QQ
				let data = res;
				uni.requestPayment({
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.package,
					signType: 'MD5',
					paySign: data.paySign,
					success: res => {
						uni.showToast({ title: '支付成功', icon: 'none' });
						// 更改用户信息
						this.getUserInfo();
						this.orders[this.swiperCurrentIndex] = [];
						// 刷新当前页面
						this.__init();
					},
					fail: res => {
						uni.showToast({ title: '支付失败', icon: 'none' });
					},
					complete: () => {
						this.submitPay = true;
					}
				});
				// #endif
				// #ifdef APP-PLUS
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: res,
					success: e => {
						uni.showToast({ title: '支付成功', icon: 'none' });
						// 更改用户信息
						this.getUserInfo();
						this.orders[this.swiperCurrentIndex] = [];
						// 刷新当前页面
						this.__init();
					},
					fail: e => {
						console.log(e);
						uni.showToast({ title: '支付失败', icon: 'none' });
					},
					complete: () => {
						this.submitPay = true;
					}
				});
				// #endif
			}
		},
		// 查看物流
		gotoLogistice(id) {
			console.log('id', id);
			uni.navigateTo({
				url: '/pages/order/orderLogistics/orderLogistics?orderId=' + id
			});
		},
		// 确认收货
		takeOverFn(orderId) {
			if (this.submitPay) {
				this.submitPay = false;
				this.$HTTP.post('/api/api.php', { act: 'confirm', order_id: orderId }, { token: true });
				setInterval(() => {
					uni.$emit('takeOverStatus');
					this.submitPay = true;
				}, 1000);
			}
		}
	},
	filters: {
		filterTime(value) {
			return moment(value).format('YYYY-MM-DD');
		}
	},
	components: { gracePage, graceNavBar, graceEmpty, graceLoading, graceFullLoading }
};
</script>
<style scoped>
@import '@/graceUI/animate.css';
.z-index-9999999 {
	z-index: 9999999;
}
.empty-view {
	margin-top: 30rpx;
}
.grace-order {
	background-color: #ffffff;
	padding: 20rpx;
	margin: 0 25rpx;
	border-radius: 10rpx;
	margin-top: 30rpx;
	width: 660rpx;
}
.grace-shop {
	line-height: 60rpx;
	font-size: 28rpx;
	font-weight: bold;
	color: #333333;
}
.grace-order-goods {
	font-size: 0;
	overflow: hidden;
	width: 660rpx;
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	align-items: center;
	padding-bottom: 20rpx;
}
.grace-order-goods-img {
	width: 100rpx;
	height: 100rpx;
}
.grace-order-goods-name {
	line-height: 40rpx;
	width: 100rpx;
	flex: auto;
	overflow: hidden;
	font-size: 26rpx;
	margin: 0 20rpx;
	color: #333333;
}
.grace-order-goods-price {
	font-size: 30rpx;
	line-height: 50rpx;
	color: #333333;
	padding-left: 10rpx;
	font-weight: bold;
}
.grace-order-goods-num {
	font-size: 22rpx;
	color: #999999;
	margin-left: 10rpx;
}
.icon-close {
	font-size: 28rpx;
	color: #999999;
	margin-left: 30rpx;
}
.grace-order-footer {
	margin-top: 2px;
}
.grace-order-number {
	line-height: 50rpx;
	color: #999999;
	font-size: 26rpx;
	width: 100rpx;
	flex: auto;
}
.grace-order-status {
	line-height: 50rpx;
	color: #999999;
	font-size: 26rpx;
	width: 100rpx;
	flex: auto;
	text-align: center;
}
.grace-order-btn {
	display: block;
	width: 150rpx;
	height: 50rpx;
	line-height: 50rpx;
	color: #999999;
	font-size: 22rpx;
	text-align: center;
	border-radius: 60rpx;
	border: 1px solid #999999;
	margin-left: 20rpx;
}
.grace-order-btn-red {
	border-color: #ff0036;
	color: #ff0036;
}
.grace-order-btn-blue {
	border-color: #3688ff;
	color: #3688ff;
}
.grace-order-btn-gray {
	border-color: #999999;
	color: #999999;
}

/* 自定义动画效果、时间、循环 */
.lodingAnimation {
	animation: fadeIn 1s linear;
}
</style>
